package handler

import (
	"fmt"
	"go-devops/common"
	"go-devops/domain/dto"
	"log"
	"path/filepath"
)

type NodeJsTaskHandler struct {
	CommonTaskHandler
}

func NewNodeJsTaskHandler() *NodeJsTaskHandler {
	return &NodeJsTaskHandler{
		CommonTaskHandler: CommonTaskHandler{},
	}
}

type NodeJsData struct {
	DockerImage string `json:"dockerImage"`
	Command     string `json:"command"`
	WorkDir     string `json:"workDir"`
}

func getNodeJsData(context *dto.NodeContext) NodeJsData {
	data := context.TaskData.Data
	jsonString := common.JsonString(data)
	var nodeJsData NodeJsData
	common.ParseJson(jsonString, &nodeJsData)
	return nodeJsData
}

func (c NodeJsTaskHandler) Stop(context *dto.NodeContext) error {
	context.StopFlag = true
	dockerId := context.DockerId
	if len(dockerId) <= 0 {
		return nil
	}

	command := fmt.Sprintf("docker stop %s", dockerId)
	err := ExecCmd(context, command, context.Workspace, true)
	return err
}

func (c NodeJsTaskHandler) HandleNode(nodeContext *dto.NodeContext) error {
	return c.Handle(nodeContext, func() error {
		data := getNodeJsData(nodeContext)
		log.Printf("nodeJs data:%v\n", data)

		dockerImage := data.DockerImage
		if len(dockerImage) <= 0 {
			return fmt.Errorf("节点镜像不能为空")
		}
		log.Printf("节点镜像：%s\n", dockerImage)
		sendMsg(nodeContext, true, fmt.Sprintf("节点镜像：%s", dockerImage))

		workspace := nodeContext.Workspace
		if len(data.WorkDir) > 0 {
			workspace = filepath.Join(workspace, data.WorkDir)
		}
		log.Printf("工作目录：%s\n", workspace)
		sendMsg(nodeContext, true, fmt.Sprintf("工作目录：%s", workspace))

		node := common.Config.Node

		command := fmt.Sprintf("docker run -i --name %s --rm -v %s:%s -w %s %s /bin/bash -c '%s'",
			nodeContext.DockerId, workspace, node.DockerPath, node.DockerPath, dockerImage, data.Command)

		if err := ExecCmd(nodeContext, command, workspace, true); err != nil {
			return err
		}
		return nil
	})
}
